<template>
  <div>
    <div class="table-link-card">
      <div style="width: '100%'; height: '100%'">
        <div v-if="showButton" class="card-button">
          <a-button @click="handleAddRecord">
            <template #default>
              <PlusOutlined />
              记 录
            </template>
          </a-button>
        </div>
        <a-row>
          <Fragment v-for="(record, index) in selectRecords" :key="index">
            <a-col :span="itemSpan">
              <div class="card-item ${detail == true? 'disabled-chunk': ''}" @click="handleClickEdit(e, record)">
                <div class="card-item-left ${showImage == true? 'show-right-image': ''}">
                  <span v-if="disabled" class="card-delete">
                    <minus-circle-filled @click="handleDeleteRecord(e, index)" />
                    <div class="card-inner">
                      <div class="card-main-content">
                        {{ getMainContent(record) }}
                        <div class="other-content">
                          <a-row>
                            <Fragment v-for="col in realShowColumns" :key="col.dataIndex">
                              <a-col :span="columnSpan">
                                <span class="label ellipsis">{{ col.title }}</span>
                                <span class="text ellipsis">{{ record[col.dataIndex] }}</span>
                              </a-col>
                            </Fragment>
                          </a-row>
                        </div>
                      </div>
                    </div>
                  </span>
                </div>
                <div v-if="showImage" class="card-item-image"> <img v-if="getImageSrc(record)" :src="getImageSrc(record2)" alt="" /> </div>
              </div>
            </a-col>
          </Fragment>
        </a-row>
      </div>
    </div>
    <online-pop-list-modal @register="registerListModal" :multi="multi" :id="popTableName" :addAuth="auths.add" :onSuccess="setup.addCard" />
    <online-pop-modal @register="registerFormModal" :id="popTableName" @success="updateCardData" topTip="" />
  </div>
</template>
<script lang="ts">
  import { ref, watch, computed, defineComponent } from 'vue';
  import { propTypes } from '/@/utils/propTypes';
  import { PlusOutlined, MinusCircleFilled } from '@ant-design/icons-vue';
  import { useModal } from '/@/components/Modal';
  import OnlinePopListModal from '../../auto/comp/OnlinePopListModal.vue';
  import OnlinePopModal from '../../auto/comp/OnlinePopModal.vue';
  import { useLinkTable } from '../../use/useAutoForm';

  export default defineComponent({
    name: 'LinkTableCard',
    props: {
      valueField: propTypes.string.def(''),
      textField: propTypes.string.def(''),
      tableName: propTypes.string.def(''),
      multi: propTypes.bool.def(false),
      value: propTypes.oneOfType([propTypes.string, propTypes.number]),
      linkFields: propTypes.array.def([]),
      disabled: propTypes.bool.def(false),
      detail: propTypes.bool.def(false),
      imageField: propTypes.string.def([]),
    },
    components: {
      PlusOutlined,
      MinusCircleFilled,
      OnlinePopListModal,
      OnlinePopModal,
    },
    emits: ['change', 'update:value'],
    setup(props, { emit }) {
      const popTableName = computed(() => {
        return props.tableName;
      });
      const [registerListModal, { openModal: openListModal }] = useModal();
      const [registerFormModal, { openModal: openFormModal }] = useModal();
      const selectValue = ref([]);
      const selectRecords = ref([]);
      const showButton = computed(() => {
        if (props.disabled == true) {
          return false;
        }
        if (props.multi === false) {
          if (selectRecords.value.length > 0) {
            return false;
          }
        }
        return true;
      });
      const {
        auths,
        otherColumns,
        realShowColumns,
        tableColumns,
        textFieldArray,
        transData,
        loadOne,
        compareData,
        formatData,
        initFormData,
        getImageSrc,
        showImage,
      } = useLinkTable(props);
      const itemSpan = computed(() => {
        if (props.multi === true) {
          return 12;
        }
        return 24;
      });
      const columnSpan = computed(() => {
        if (props.multi === true) {
          return 24;
        }
        return 12;
      });
      function getMainContent(record2) {
        if (record2) {
          if (textFieldArray.value.length > 0) {
            const field2 = textFieldArray.value[0];
            return record2[field2];
          }
        }
      }
      function prevent(e) {
        e == null ? void 0 : e.stopPropagation();
        e == null ? void 0 : e.preventDefault();
      }
      function handleClickEdit(e, record2) {
        prevent(e);
        if (auths.update == false) {
          console.error('当前用户无编辑权限!');
          return;
        }
        if (props.disabled == false) {
          openFormModal(true, {
            isUpdate: true,
            record: record2,
          });
        }
      }
      function handleAddRecord(e) {
        openListModal(true, {});
      }
      function addCard(data) {
        const arr = selectRecords.value;
        for (const item of data) {
          const temp = Object.assign({}, item);
          transData(temp);
          arr.push(temp);
        }
        selectRecords.value = arr;
        emitValue();
      }
      function updateCardData(formData) {
        const arr = selectRecords.value;
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].id === formData.id) {
            const temp = Object.assign({}, formData);
            transData(temp);
            arr.splice(i, 1, temp);
          }
        }
        selectRecords.value = arr;
        emitValue();
      }
      function handleDeleteRecord(e, index) {
        prevent(e);
        const temp = selectRecords.value;
        if (temp && temp.length > index) {
          temp.splice(index, 1);
          selectRecords.value = temp;
        }
        emitValue();
      }
      function emitValue() {
        const arr = selectRecords.value;
        const values = [];
        const formData = {};
        const linkFieldArray = props.linkFields;
        if (arr.length > 0) {
          for (let i = 0; i < arr.length; i++) {
            values.push(arr[i][props.valueField]);
            initFormData(formData, linkFieldArray, arr[i]);
          }
        } else {
          initFormData(formData, linkFieldArray);
        }
        const text2 = values.join(',');
        formatData(formData);
        emit('change', text2, formData);
        emit('update:value', text2);
      }
      watch(
        () => props.value,
        async (val) => {
          if (val) {
            const flag = compareData(selectRecords.value, val);
            if (flag === false) {
              const arr = await loadOne(val);
              selectRecords.value = arr;
            }
            if (props.linkFields && props.linkFields.length > 0) {
              emitValue();
            }
          } else {
            selectRecords.value = [];
          }
        },
        { immediate: true }
      );
      return {
        popTableName,
        selectRecords,
        otherColumns,
        realShowColumns,
        showButton,
        selectValue,
        handleAddRecord,
        handleDeleteRecord,
        getMainContent,
        itemSpan,
        columnSpan,
        tableColumns,
        addCard,
        registerListModal,
        registerFormModal,
        handleClickEdit,
        updateCardData,
        getImageSrc,
        showImage,
        auths,
      };
    },
  });
</script>
<style scoped>
  .table-link-card {
    box-sizing: border-box;
    position: relative;
    width: 100%;
  }

  .table-link-card .card-button {
    margin-bottom: 10px !important;
  }

  .table-link-card .card-item {
    width: calc(100%-10px);
    display: inline-flex;
    flex-direction: row;
    position: relative;
    border-radius: 3px;
    background-color: #fff;
    box-shadow: #0000001f 0 1px 4px 0 0 2px;
    cursor: pointer;
    margin: 0 10px 10px 0;
  }

  .table-link-card .card-item:hover .card-item-left .card-delete {
    display: inline-block;
  }

  .table-link-card .card-item.disabled-chunk {
    background: none;
    box-shadow: none;
  }

  .table-link-card .card-item .card-item-image {
    width: 100px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    overflow: hidden;
  }

  .table-link-card .card-item .card-item-left {
    width: 100%;
    display: inline-block;
  }

  .table-link-card .card-item .card-item-left.show-right-image {
    width: calc(100%-100px);
  }

  .table-link-card .card-item .card-item-left .card-delete {
    position: absolute;
    top: -8px;
    right: -8px;
    font-size: 16px;
    color: #757575;
    line-height: 1em;
    overflow: hidden;
    display: none;
  }

  .table-link-card .card-item .card-item-left .card-inner {
    flex: 1 1 0;
    overflow: hidden;
    padding: 12px 16px 10px;
  }

  .table-link-card .card-item .card-item-left .card-inner .card-main-content {
    overflow: hidden;
    text-overflow: ellipsis;
    vertical-align: top;
    white-space: nowrap;
    margin-bottom: 8px;
    font-weight: 500;
    font-size: 14px;
    line-height: 20px;
    color: #333;
  }

  .table-link-card .card-item .card-item-left .card-inner .other-content .text {
    font-size: 12px !important;
    display: inline-block;
    width: 80%;
  }

  .table-link-card .card-item .card-item-left .card-inner .other-content .label {
    max-width: 160px;
    color: #9e9e9e;
    padding-right: 0.7em;
    display: inline-block;
  }

  .table-link-card .card-item .card-item-left .card-inner .other-content .ellipsis {
    overflow: hidden;
    height: 22px;
    line-height: 22px;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
</style>
